<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/25 0025
 * Time: 9:19
 */
namespace app\api\controller;

use app\api\model\Api;
use app\api\model\JWT;
use think\App;
use think\Controller;
use think\Db;
use app\api\model\Role as RoleModel;

/**
 * @title 营销
 * @description 接口说明
 * @header name:flag require:1 default: desc:手机设备号
 */
class Market extends Api
{
    public function group_same_key($arr,$key)
    {
        $new_arr = array();
         foreach($arr as $k=>$v ){
            $new_arr[$v[$key]][] = $v;
        }
        return $new_arr;
    }
    /**
     * @title 营销首页
     * @description 接口说明
     * @author 开发者
     * @url /api/market/index
     * @method POST
     * @param name:begin_time type:string require:0 default: other: desc:开始时间（...-..-..）
     * @param name:end_time type:string require:0 default: other: desc:结束时间（...-..-..）
     * @param name:search type:string require:0 default: other: desc:搜索姓名或手机号
     * @param name:director_id type:int require:0 default: other: desc:客户经理id（若查看全部传空）
     * @param name:page type:int require:0 default: other: desc:页码
     * @return list:列表@
     * @list id:id bid:宴会厅id book:预订人 mobile:预订人手机号 yu_time:宴会时间 begin_night:1中午2晚上 b_name:宴会厅名称 desk:桌数 dname:套餐餐标 count:回访次数 is_meeting:1会议2不是会议 end_time:会议结束日期 addtime:下单时间  end_night:会议结束1中午2下午
     * @return total:总条数
     */
    public function index()
    {
        $user = $this->user;
        $page = input('page')??1;
        $where[] = ['hid','=',$user['hid']];
        $where[] = ['type','=',1];

        $begin_time = input('begin_time');

        $search = input('search');

        $end_time = input('end_time');
        $director_id = input('director_id');
        if($begin_time && $end_time){
            $begin = explode("-",$begin_time);
            $end = explode("-",$end_time);
            $where[] = ['begin_year','between',[$begin[0],$end[0]]];
            $where[] = ['begin_month','between',[$begin[1],$end[1]]];
            $where[] = ['begin_day','between',[$begin[2],$end[2]]];
        }
        if($director_id){
            $where[] = ['director_id','=',$director_id];
        }
        if($search){
            if(is_numeric($search)){
                $where[] = ['mobile','like',"%".$search."%"];
            }else{
                $where[] = ['book','like',"%".$search."%"];
            }
        }

        $where[] = ['is_del','=',2];
        $list = db::name('scheduled')->where($where)
        ->field('id,book,bid,mobile,begin_year,begin_month,addtime,begin_day,begin_night,desk,b_name,did,is_meeting,end_year,end_month,end_day,end_night')
        ->page("$page",10)->select();
        $total = db::name('scheduled')->where($where)->count();

        unset($where[1]);
        $where[] = ['type','=',2];
        $lists = db::name('scheduled')->where($where)
        ->field('id,book,bid,mobile,begin_year,begin_month,addtime,begin_day,begin_night,desk,b_name,did,is_meeting,end_year,end_month,end_day,end_night')
        ->page("$page",10)->select();

        $lists = $this->group_same_key($lists,'is_meeting');
        // print_r($total);die;

        if(isset($lists[2])){
            $noMeeting = $lists[2];
        }else{
            $noMeeting = [];
        }
        if(isset($lists[1])){
            $isMeeting = $lists[1];
        }else{
            $isMeeting = [];
        }
        $i = 0;
        // foreach ($list as $ks => $vs) {
        //     foreach ($noMeeting as $nk => $nv) {
        //         if($vs['begin_year'] == $nv['begin_year'] && $vs['begin_month'] == $nv['begin_month'] && $vs['begin_day'] == $nv['begin_day'] && $vs['begin_night'] == $nv['begin_night'] && $vs['bid'] == $nv['bid']){
        //             unset($list[$ks]);
        //             $total - 1;
        //         }
        //     }
        // }
        // foreach ($list as $ks => $vs) {
        //     if($isMeeting){
        //         foreach ($isMeeting as $mk => $mv) {
        //             $meetingBegin = $mv['begin_year'] . '-' .$mv['begin_month'] . '-' .$mv['begin_day'];
        //             $meetingEnd = $mv['begin_year'] . '-' .$mv['begin_month'] . '-' .$mv['begin_day'];
        //             $banquetBegin = $vs['begin_year']. '-' .$vs['begin_month'] . '-' .$vs['begin_day'];
        //             $meetingBegin = strtotime($meetingBegin);
        //             $meetingEnd = strtotime($meetingEnd);
        //             $banquetBegin = strtotime($banquetBegin);
        //             if($banquetBegin >= $meetingBegin && $banquetBegin <= $meetingEnd){
        //                 unset($list[$ks]);
        //                 $total - 1;
        //             }
        //         }
        //     }
            
        // }
        $new_arr = [];
        foreach ($list as $k => $v) {
            if($v['bid']){
                $is_del = db::name('banquet')->where('id',$v['bid'])->value('is_del');
                if($is_del == 2){
                    unset($list[$k]);
                    $total - 1;
                    break;
                }
            }
            $list[$k]['yu_time'] = $v['begin_year'].'-'.$v['begin_month'].'-'.$v['begin_day'];
            unset($list[$k]['begin_year']);
            unset($list[$k]['begin_month']);
            unset($list[$k]['begin_day']);
            if($v['did']){
                $list[$k]['dname'] = db::name('ds')->where('id',$v['did'])->value('name');
            }else{
                $list[$k]['dname'] = '自选餐标';
            }
            $wheres[] = ['hid','=',$user['hid']];
            // $wheres[] = ['uid','=',$user['id']];
            $wheres[] = ['did','=',$v['id']];
            $count = db::name('visit')->where($wheres)->count();
            $list[$k]['count'] = $count;
            if($v['is_meeting'] == 1){
                $list[$k]['end_time'] = $v['end_year'].'-'.$v['end_month'].'-'.$v['end_day'];
                unset($list[$k]['end_year']);
                unset($list[$k]['end_month']);
                unset($list[$k]['end_day']);
                unset($list[$k]['did']);
            }else{
                $list[$k]['end_time'] = '';
                unset($list[$k]['end_year']);
                unset($list[$k]['end_month']);
                unset($list[$k]['end_day']);
                unset($list[$k]['did']);
            }
            $wheres = [];
            $list[$k]['addtime'] =  date('Y-m-d H:i:s',$v['addtime']);
        }
        $data['list'] = array_merge($list,$new_arr);
        $data['page'] = ceil($total/10);
        $data['total'] = $total;
        return $this->ajaxReturn(0,'成功',$data);
    }
    /**
     * @title 获取历史回访
     * @description 接口说明
     * @author 开发者
     * @url /api/market/history
     * @method POST
     * @param name:id type:int require:1 default: other: desc:订单id
     * 
     * @return list:列表@
     * @list id:id addtime:回访时间 manager:跟进人 type:方式1电话2微信3面谈 content:回访内容 image:回访图片
     * 
     */
    public function history()
    {
        $user = $this->user;
        $page = input('page')??1;
        if(!input('id')){
            return $this->ajaxReturn(1,'缺少参数');
        }
        $id = input('id');
        // $where[] = ['uid','=',$user['id']];
        $where[] = ['hid','=',$user['hid']];
        $where[] = ['did','=',$id];
        $dir = db::name('scheduled')->where('id',$id)->find();
        if(!$dir){
            return $this->ajaxReturn(1,'订单异常');
        }




        $list = db::name('visit')->where($where)
        ->field('id,uid,addtime,type,content,other,time')
        ->order('addtime desc')
        ->page("$page,10")->select();
        $total = db::name('visit')->where($where)->count();
        foreach ($list as $k => $v) {
            $list[$k]['manager'] =  db::name('user')->where('id',$v['uid'])->value('username');
            if($v['other']){
                $image = explode( ",",$v['other']);
                if(count($image) != 1){
                    $pic = array();
                    foreach($image as $vs){
                        $pic[] = get_file_path($vs);
                    }
                    $list[$k]['image'] = $pic;
                }else{
                    $pics = array();
                    $pics[] = get_file_path($v['other']);
                    $list[$k]['image'] = $pics;
                }
            }else{
                $list[$k]['image'] = '';
            }
            unset($list[$k]['other']);
            unset($list[$k]['uid']);
            $list[$k]['addtime'] = $v['time'];
        }

        if($dir['director_id'] != $user['id']){
            $pid = db::name('admin_role')->where('id','in',$user['role'])->field('pid')->select();
            $pids = 0;
            foreach ($pid as $vs) {
                if($vs['pid'] == 0){
                    $pids = 1;
                    break;
                }else{
                    $pids = 2;
                }
            }
            if($pids == 2){
                $res = RoleModel::roleAuth($user['role']);
                $newArrs = [];
                if($res){
                    foreach ($res as $k => $v) {
                        $str1 =str_replace("[","",$res[$k]);
                        $str1 =str_replace("]","",$str1);
                        $newArr = explode(',',$str1);
                        $newArrs = array_merge($newArr,$newArrs);
                    }
                    foreach ($newArrs as $kn => $vn) {
                        $vn =str_replace('"',"",$vn);
                        $newArrs[$kn] = $vn;
                    }
                    if(!in_array('309',$newArrs)){
                        $list = [];
                    }
                }
            } 
        }

       
        $data['list'] = $list;
        return $this->ajaxReturn(0,'成功',$data);
    }
    /**
     * @title 添加回访
     * @description 接口说明
     * @author 开发者
     * @url /api/market/history_save
     * @method POST
     * @param name:id type:int require:1 default: other: desc:订单id
     * @param name:time type:string require:1 default: other: desc:回访时间（....-..-..）
     * @param name:content type:string require:1 default: other: desc:回访内容
     * @param name:other type:string require:0 default: other: desc:其他信息（图片id逗号隔开）
     * @param name:type type:int require:1 default: other: desc:1电话2微信3面谈
     * 
     */
    public function history_save()
    {
        $user = $this->user;
        $page = input('page')??1;
        if(!input('id')){
            return $this->ajaxReturn(1,'缺少参数');
        }
        $id = input('id');
        $dir = db::name('scheduled')->where('id',$id)->find();
        if(!$dir){
            return $this->ajaxReturn(1,'订单异常');
        }
        if($dir['director_id'] != $user['id']){
            $pid = db::name('admin_role')->where('id','in',$user['role'])->field('pid')->select();
            $pids = 0;
            foreach ($pid as $vs) {
                if($vs['pid'] == 0){
                    $pids = 1;
                    break;
                }else{
                    $pids = 2;
                }
            }
            if($pids == 2){
                $res = RoleModel::roleAuth($user['role']);
                $newArrs = [];
                if($res){
                    foreach ($res as $k => $v) {
                        $str1 =str_replace("[","",$res[$k]);
                        $str1 =str_replace("]","",$str1);
                        $newArr = explode(',',$str1);
                        $newArrs = array_merge($newArr,$newArrs);
                    }
                    foreach ($newArrs as $kn => $vn) {
                        $vn =str_replace('"',"",$vn);
                        $newArrs[$kn] = $vn;
                    }
                    if(!in_array('308',$newArrs)){
                        return $this->ajaxReturn(1,'暂无添加回访权限');
                    }
                }
            } 
        }


        $id = input('id');
        $time = input('time');
        $content = input('content');
        $other = input('other');
        $type = input('type');

        $data['hid'] = $user['hid'];
        $data['uid'] = $user['id'];
        $data['time'] = $time;
        $data['type'] = $type;
        $data['content'] = $content;
        $data['other'] = $other;
        $data['did'] = $id;
        $data['addtime'] = time();
        db::name('visit')->insert($data);
        return $this->ajaxReturn(0,'成功');
    }
    /**
     * @title TOP榜
     * @description 接口说明
     * @author 开发者
     * @url /api/market/top
     * @method POST
     * @param name:type type:int require:1 default: other: desc:1近七天2三十天3九十天
     * @param name:is_type type:int require:1 default: other: desc:1场数2桌数3押金
     * @param name:page type:int require:1 default: other: desc:页码
     * 
     * 
     * @return list:列表@
     * @list id:id username:昵称 avatar:头像 num:数量
     * @return total:总页数
     * 
     */
    public function top()
    {
        $user = $this->user;
        $page = input('page')??1;
        $type = input('type');
        $is_type = input('is_type')??2;

        $pid = db::name('admin_role')->where('id','in',$user['role'])->field('pid')->select();
        $pids = 0;
        foreach ($pid as $vs) {
            if($vs['pid'] == 0){
                $pids = 1;
                break;
            }else{
                $pids = 2;
            }
        }
        if($pids == 2){
            $res = RoleModel::roleAuth($user['role']);
            $newArrs = [];
            if($res){
                foreach ($res as $k => $v) {
                    $str1 =str_replace("[","",$res[$k]);
                    $str1 =str_replace("]","",$str1);
                    $newArr = explode(',',$str1);
                    $newArrs = array_merge($newArr,$newArrs);
                }
                foreach ($newArrs as $kn => $vn) {
                    $vn =str_replace('"',"",$vn);
                    $newArrs[$kn] = $vn;
                }
                if(!in_array('331',$newArrs)){
                    return $this->ajaxReturn(1,'暂无查看权限');
                }
            }
        }

        if(!$type){
            $type = 1;
        }
        if(!$is_type){
            $is_type = 2;
        }
        $users =  db::name('user')->where('hid','=',$user['hid'])->field('id,username,avatar,hid')->page("$page,10")->select();
        $total = db::name('user')->where('hid','=',$user['hid'])->count();
        if($type == 1){
            $time = strtotime('-7 days');
        }elseif($type == 2){
            $time = strtotime('-30 days');
        }elseif($type == 3){
            $time = strtotime('-90 days');
        }
        foreach ($users as $k => $v) {
            $users[$k]['avatar'] = get_file_path($v['avatar']);
            $times = time();
            $where[] = ['hid','=',$v['hid']];
            $where[] = ['director_id','=',$v['id']];
            $where[] = ['type','=',2];
            $where[] = ['paytime','between',[$time,$times]];
            $where[] = ['is_del','=',2];
            if($is_type == 1){
               $users[$k]['num'] = db::name('scheduled')->where($where)->count();
               $where = [];
            }elseif($is_type == 2){
                $users[$k]['num'] = db::name('scheduled')->where($where)->sum('desk');
                $where = [];
            }elseif($is_type == 3){
                $wheres[] = ['hid','=',$v['hid']];
                $wheres[] = ['manager_id','=',$v['id']];
                $wheres[] = ['status','between',[2,3]];
                $wheres[] = ['addtime','between',[$time,$times]];
                $users[$k]['num'] = db::name('scheduled_deposit')->where($wheres)->sum('money');
                $wheres = [];
            }
            unset($users[$k]['hid']);
        }
        $usera = array_column($users, 'num');
        array_multisort($usera, SORT_DESC, $users);
        $data['list'] = $users;
        $data['page'] = ceil($total/10);
        $data['total'] = $total;
        return $this->ajaxReturn(0,'成功',$data);
    }
}